//
//  BaseWebViewController.m
//  YFZShoppingMall
//
//  Created by Coder on 16/7/5.
//  Copyright © 2016年 BJY12. All rights reserved.
//

#import "BaseWebViewController.h"
#import "NJKWebViewProgressView.h"
#import "UIBarButtonItem+CommomBarButtonItem.h"
#import "MainWebViewController.h"
#import "AppConfig.h"
#import "AppDelegate.h"
#import "CommentViewController.h"
#import "WXApi.h"
#import "AFNetworking.h"
#import <AVFoundation/AVFoundation.h>
#import "QRCodeGenerateVC.h"
#import "SGQRCodeScanningVC.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "SecondWebViewViewController.h"
#import "SDPhotoBrowser.h"
#import "UIImageView+WebCache.h"
#import "UIImage+GIF.h"
#import "YBPopupMenu.h"

#define TITLES @[@"首页", @"帮助", @"分享",]
#define ICONS  @[@"pop_main",@"pop_help",@"pop_share"]

@interface BaseWebViewController ()<UIActionSheetDelegate,SDPhotoBrowserDelegate,YBPopupMenuDelegate>
@property (nonatomic, strong)UIActionSheet *actionSheet;
@property (nonatomic, strong) YBPopupMenu *popupMenu;
@property (nonatomic, strong) UIButton *rightBtn;

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UIImageView *imgV;
@end

@implementation BaseWebViewController
{
    NJKWebViewProgressView *_progressView;
    NJKWebViewProgress *_progressProxy;
    BOOL firstTimaIntoWebView;
    BOOL netWorking;
    NSTimer *timer;
    BOOL timeOut;
    NSString *urlStr;
    int flistShowNum;
    NSString *baseUrl;
    NSMutableArray *_imageArray;
    NSMutableArray *_imageUrlArray;
    NSMutableArray *_imageUrlArray2;
    UIView *contenterView;
}
@synthesize userDefaults;
@synthesize defaultUrl;//默认打开的URL
@synthesize ShowFullLoadingView;//网页加载时显示全屏加载图
@synthesize OpenUrlInNewWeb;
@synthesize AlwaysInThisWebView;//总是在当前视图打开链接
@synthesize RefreshWhenAppear;//每次视图显示都刷新网页

- (void)dealloc
{
    [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
}
-(void)loadView
{
    [super loadView];
    
    //首次加载网页在当前web中显示
    OpenUrlInNewWeb=NO;
    //不是刷新加载，显示全屏动画加载
    ShowFullLoadingView=YES;
    firstTimaIntoWebView = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets=NO;
    userDefaults = [NSUserDefaults standardUserDefaults];
    self.view.backgroundColor=[UIColor whiteColor];
    
    
    flistShowNum = 0;
    [self initSatusBar];
    [self initNavigation2];
    [self initwebView];
    
    // 2.集成刷新控件
    [self setupRefresh];
    
    
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(mytest:) name:NFC_didBecomeActive object:nil];

}

- (void) mytest:(NSNotification*) notification

{
    //刷新界面
    
    if (firstTimaIntoWebView) {
        firstTimaIntoWebView = NO;
    }else{
        [baseWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
    }
    
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (defaultUrl&&![@"" isEqualToString:defaultUrl]) {
        //网页重载
        NSString* nowUrl= baseWebView.request.URL.absoluteString;
        
        if (nowUrl==nil || [nowUrl isEqualToString:@""]) {
            [self webViewLoadURL:self.defaultUrl];
        }else{
            if (RefreshWhenAppear) {
                //[self refleshWeb];
                [self refleshWebWithLoadingView];
            }
        }
    }
    
    [self.view addSubview:_progressView];
    
}


//下拉刷新
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    // 添加下拉刷新控件
    baseWebView.scrollView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        OpenUrlInNewWeb = NO;
        ShowFullLoadingView=NO;
        [baseWebView reload];
    }];
}

#pragma mark - StatusBar方法
//设置状态栏颜色
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

-(void)initSatusBar
{
    [self.navigationController.navigationBar setTranslucent:NO];//设置navigationbar的半透明
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];//设置状态栏字体颜色为白色
    

    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    [self setStatusBarBackgroundColor:[UIColor colorWithRed:255.0/255 green:255.0/255 blue:255.0/255 alpha:1]];
}

-(void)initNavigation2
{
    self.navigationItem.leftBarButtonItems  = NULL;
    self.navigationItem.rightBarButtonItem  = NULL;
    //设置导航栏样式
    [self.navigationController.navigationBar setBarTintColor:UIMainNavi];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor],UITextAttributeTextColor,nil]];
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem createBackBBTframe:CGRectMake(0, 0, 50, self.navigationController.navigationBar.bounds.size.height) isShowArrow:YES isShowTitle:NO target:self action:@selector(finishActivty)];
    
    //标题栏字体大小
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor],UITextAttributeTextColor,[UIFont systemFontOfSize:22],UITextAttributeFont, nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    
}

-(void)initwebView{
    contenterView = [[UIView alloc] init];
    contenterView.center = self.view.center;
    [self.view addSubview:contenterView];
    
    //初始化WebView代理
    _progressProxy = [[NJKWebViewProgress alloc] init];
    
    //初始化浏览器
    
    baseWebView = [[UIWebView alloc]initWithFrame:CGRectZero];
    if (self.view.bounds.size.height == 812) {
        baseWebView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-34);
    }
    else {
        baseWebView.frame = CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT-20);
    }
    //[webView.scrollView setContentInset:UIEdgeInsetsMake(44+20,0,Tabbar_Height,0)];
    [baseWebView.scrollView setContentInset:UIEdgeInsetsMake(44+20,0,0,0)];
    baseWebView.delegate = _progressProxy;
    baseWebView.opaque = NO;
    baseWebView.scrollView.bounces=YES;
    baseWebView.backgroundColor = COLOR_BGView;
    

    
    //请求超时，后在webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error中做超时提醒
    //    NSURL *urltest=[NSURL URLWithString:@"http://www.baidu.com"];
    //    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:urltest
    //
    //                                                  cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
    //
    //                                              timeoutInterval:8];
    
    //把cookie给set进WebView中,一定要在loadRequest之前设置cookie
    NSArray *cookies =[[NSUserDefaults standardUserDefaults]  objectForKey:@"cookies"];
    if (cookies) {
        NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
        [cookieProperties setObject:[cookies objectAtIndex:0] forKey:NSHTTPCookieName];
        [cookieProperties setObject:[cookies objectAtIndex:1] forKey:NSHTTPCookieValue];
        [cookieProperties setObject:[cookies objectAtIndex:3] forKey:NSHTTPCookieDomain];
        [cookieProperties setObject:[cookies objectAtIndex:4] forKey:NSHTTPCookiePath];
        NSHTTPCookie *cookieuser = [NSHTTPCookie cookieWithProperties:cookieProperties];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage]  setCookie:cookieuser];
    }
    
    
    //    [webView loadRequest:request];
    
    
    
    
    [self.view addSubview:baseWebView];
    
    //设置WebView代理对象的代理
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    
    //添加WebView代理的进度条视图
    CGFloat progressBarHeight = 2.f;
    CGRect navigaitonBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, 20, navigaitonBarBounds.size.width, progressBarHeight);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [_progressView setTintColor:[UIColor colorWithRed:255/255.0 green:0 blue:0 alpha:1]];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - webviewDelegate
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *currentUrl=request.URL;
    urlStr=currentUrl.absoluteString;//原始链接，微信支付不能使用全小写参数
    NSString *stringUrl = [urlStr lowercaseString];//转成小写的链接，用于判断业务
    
    
    if ([stringUrl rangeOfString:@"mqq://im/chat?"].location != NSNotFound) {
        
        MainWebViewController*mainWebVC = [[MainWebViewController alloc]init];
        mainWebVC.defaultUrl = stringUrl;
        //            mainWebVC.RefreshWhenAppear=YES;
        mainWebVC.AlwaysInThisWebView = YES;
        mainWebVC.isSharekView = YES;
        [self.navigationController pushViewController:mainWebVC animated:YES];
        
        return NO;
    }
    if ([stringUrl rangeOfString:@"home/qrcode"].location  != NSNotFound) {
        
        //设置扫码区域参数
        
        // 1、 获取摄像设备
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if (device) {
            AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (status == AVAuthorizationStatusNotDetermined) {
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    if (granted) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            SGQRCodeScanningVC *vc = [[SGQRCodeScanningVC alloc] init];
                            [self.navigationController pushViewController:vc animated:YES];
                        });
                        
                        NSLog(@"当前线程 - - %@", [NSThread currentThread]);
                        // 用户第一次同意了访问相机权限
                        NSLog(@"用户第一次同意了访问相机权限");
                        
                    } else {
                        
                        // 用户第一次拒绝了访问相机权限
                        NSLog(@"用户第一次拒绝了访问相机权限");
                    }
                }];
            } else if (status == AVAuthorizationStatusAuthorized) { // 用户允许当前应用访问相机
                SGQRCodeScanningVC *vc = [[SGQRCodeScanningVC alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            } else if (status == AVAuthorizationStatusDenied) { // 用户拒绝当前应用访问相机
                UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 相机 - SGQRCodeExample] 打开访问开关" preferredStyle:(UIAlertControllerStyleAlert)];
                UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                
                [alertC addAction:alertA];
                [self presentViewController:alertC animated:YES completion:nil];
                
            } else if (status == AVAuthorizationStatusRestricted) {
                NSLog(@"因为系统原因, 无法访问相册");
            }
        } else {
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"未检测到您的摄像头" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [alertC addAction:alertA];
            [self presentViewController:alertC animated:YES completion:nil];
        } 

        
        return NO;
    }
    if ([stringUrl rangeOfString:@"teacher/scancodepay"].location != NSNotFound) {
        
        //设置扫码区域参数
        
        // 1、 获取摄像设备
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if (device) {
            AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (status == AVAuthorizationStatusNotDetermined) {
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    if (granted) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            SGQRCodeScanningVC *vc = [[SGQRCodeScanningVC alloc] init];
                            [self.navigationController pushViewController:vc animated:YES];
                        });
                        
                        NSLog(@"当前线程 - - %@", [NSThread currentThread]);
                        // 用户第一次同意了访问相机权限
                        NSLog(@"用户第一次同意了访问相机权限");
                        
                    } else {
                        
                        // 用户第一次拒绝了访问相机权限
                        NSLog(@"用户第一次拒绝了访问相机权限");
                    }
                }];
            } else if (status == AVAuthorizationStatusAuthorized) { // 用户允许当前应用访问相机
                SGQRCodeScanningVC *vc = [[SGQRCodeScanningVC alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            } else if (status == AVAuthorizationStatusDenied) { // 用户拒绝当前应用访问相机
                UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 相机 - SGQRCodeExample] 打开访问开关" preferredStyle:(UIAlertControllerStyleAlert)];
                UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                
                [alertC addAction:alertA];
                [self presentViewController:alertC animated:YES completion:nil];
                
            } else if (status == AVAuthorizationStatusRestricted) {
                NSLog(@"因为系统原因, 无法访问相册");
            }
        } else {
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"未检测到您的摄像头" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [alertC addAction:alertA];
            [self presentViewController:alertC animated:YES completion:nil];
        }
        
        
        return NO;
    }
    
    if ([stringUrl rangeOfString:@"activities/list"].location != NSNotFound) {
        
        if ([baseWebView canGoBack]) {
            
            SecondWebViewViewController *secondWebViewVC = [[SecondWebViewViewController alloc] init];
            secondWebViewVC.listString = stringUrl;
            [self.navigationController pushViewController:secondWebViewVC animated:YES];
            
            return NO;

        }
    }
   
    NSString *titleString = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    if ([titleString isEqualToString:@"礼包详情-众乐城"]) {
        if ([stringUrl rangeOfString:@"eidtor/image"].location != NSNotFound) {
            if ([request.URL.scheme isEqualToString:@"image-preview"]) {
                NSString* path = [request.URL.absoluteString substringFromIndex:[@"image-preview:" length]];
                path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                NSInteger index = 0;
                
                for (NSInteger i = 0; i<_imageUrlArray.count; i++) {
                    if ([path isEqualToString:_imageUrlArray[i]]) {
                        index = i;
                    }
                }
                
                SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
                browser.currentImageIndex = index;
                browser.sourceImagesContainerView = contenterView;
                browser.imageCount = _imageUrlArray.count;
                browser.delegate = self;
                [browser show];
                
                return NO;
            }
        }
    }
    else {
        if ([request.URL.scheme isEqualToString:@"image-preview"]) {
            NSString* path = [request.URL.absoluteString substringFromIndex:[@"image-preview:" length]];
            path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSInteger index = 0;
            
            for (NSInteger i = 0; i<_imageUrlArray.count; i++) {
                if ([path isEqualToString:_imageUrlArray[i]]) {
                    index = i;
                }
            }
            
            SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
            browser.currentImageIndex = index;
            browser.sourceImagesContainerView = contenterView;
            browser.imageCount = _imageUrlArray.count;
            browser.delegate = self;
            [browser show];
            
            return NO;
        }
    
    }
    
   

    
    
    //    //判断是不是微信支付页面
    //    NSRange foundObj=[stringUrl rangeOfString:@"/weixin/pay" options:NSCaseInsensitiveSearch];
    //    if(foundObj.length>0) {
    //        //判断用户是否安装了微信
    //        if([WXApi isWXAppInstalled])
    //        {
    //            [self dealWithWeiXinPay:urlStr];
    //            return YES;
    //        }else{
    //            UIAlertView *alert = [[UIAlertView alloc]
    //                                  initWithTitle:@"提示"
    //                                  message:@"您还没有安装微信呢，不能使用微信进行支付哟~~"
    //                                  delegate:self
    //                                  cancelButtonTitle:@"好"
    //                                  otherButtonTitles:nil
    //                                  ];
    //            alert.tag = 0;
    //            [alert show];
    //            return NO;
    //        }
    //    }
    
    
    
    
    //原生的评论界面
    //    if ([stringUrl rangeOfString:@"comment/tradecomment"].location != NSNotFound) {
    //        //把字符串？号分作两节来截取后面的tradeid的值
    //
    //
    //        NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    //        NSArray *cookies = [sharedHTTPCookieStorage cookiesForURL:[NSURL URLWithString:stringUrl]];
    //        NSEnumerator *enumerator = [cookies objectEnumerator];
    //        NSHTTPCookie *cookie;
    //
    //        NSString * cookielong;
    //
    //        while (cookie = [enumerator nextObject]) {
    //            NSLog(@"COOKIE{name: %@, value: %@}", [cookie name], [cookie value]);
    //
    //            if ([[cookie name] isEqualToString:@"Members"]) {
    //                cookielong = [cookie value];
    //            }
    //
    //        }
    //
    //
    //
    //
    //        NSLog(@"---cookielong{%@}---", [cookielong substringFromIndex:5]);
    //
    //        NSArray *strarray = [stringUrl componentsSeparatedByString:@"?"];
    //        CommentViewController * commentVC = [[CommentViewController alloc]init];
    //        commentVC.tradeid = [strarray[1] substringFromIndex:8];
    //        commentVC.userCookies= [cookielong substringFromIndex:5];
    //
    //        [self.navigationController pushViewController:commentVC animated:YES];
    //
    //        return NO;
    //
    //
    //    }
    
    
    
    
    
    //--------------然后检查特定网址，识别到新开特定ViewController处理(针对继承了BaseWebView的控制器)--------------------
    
    
    /*
     if (OpenUrlInNewWeb) {
     
     //详情页面 @"activities/detail"
     if ([stringUrl rangeOfString:@"activities/detail"].location != NSNotFound) {
     
     MainWebViewController*mainWebVC = [[MainWebViewController alloc]init];
     mainWebVC.defaultUrl = stringUrl;
     //            mainWebVC.RefreshWhenAppear=YES;
     mainWebVC.AlwaysInThisWebView = YES;
     mainWebVC.isSharekView = YES;
     [self.navigationController pushViewController:mainWebVC animated:YES];
     
     return NO;
     }
     
     
     
     //确认提交订单
     if ([stringUrl rangeOfString:@"order/rstcart"].location != NSNotFound) {
     MainWebViewController*mainWebVC = [[MainWebViewController alloc]init];
     mainWebVC.defaultUrl = stringUrl;
     mainWebVC.AlwaysInThisWebView=YES;
     [self.navigationController pushViewController:mainWebVC animated:YES];
     
     return NO;
     }
     
     
     //其他网页链接
     MainWebViewController *newWeb=[[MainWebViewController alloc]init];
     [newWeb setDefaultUrl:urlStr];
     [self.navigationController pushViewController:newWeb animated:YES];
     
     return NO;
     }
     
     
     //---------------------------在本视图控制器要处理的操作-----------------------------
     
     
     
     
     */
    
    
    
    //显示加载图

    [self showLoadingView];
        

    
    NSLog(@"请求：%@",stringUrl);
    return YES;
}
-(void)finishActivty
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)showLoadingView
{
    if (flistShowNum == 0) {
        [baseWebView setHidden:YES];
        if (loadingView==nil) {
            //计算
            int width=100;
            int height=100;
            int y=SCREEN_HEIGHT*0.4-(width/2);
            int x=(SCREEN_WIDTH-width)/2;
            
            NSData *data=[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"loading" ofType:@"gif"]];
            
            loadingView=[[UIWebView alloc] initWithFrame:CGRectMake(x,y, width, height)];
            loadingView.backgroundColor=[UIColor clearColor];
            loadingView.opaque=NO;
            loadingView.scrollView.bounces=NO;
            loadingView.scalesPageToFit=YES;
            [loadingView loadData:data MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
        }
        
        
        [self.view addSubview:loadingView];

    }
    else {
        [baseWebView setHidden:NO];
        [loadingView removeFromSuperview];
    }
    flistShowNum++;
    
}


-(void)webViewDidFinishLoad:(UIWebView *)webViewTarget
{
    timeOut = NO;
    [timer invalidate];//销毁计时器
    [baseWebView setHidden:NO];
    
    if (loadingView!=nil) {
        [self hideLoadingView];
    }
    
    [baseWebView.scrollView.mj_header endRefreshing];
    
    //优化内存，防止内存泄露
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    //获取cookie
    NSArray*nCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies];
    
    NSLog(@"---cookies:%@",nCookies);
    NSHTTPCookie*cookie;
    for (id c in nCookies)
    {
        if ([c isKindOfClass:[NSHTTPCookie class]])
        {
            cookie=(NSHTTPCookie *)c;
            if ([cookie.name isEqualToString:@"Members"]) {
                NSNumber *sessionOnly = [NSNumber numberWithBool:cookie.sessionOnly];
                NSNumber *isSecure = [NSNumber numberWithBool:cookie.isSecure];
                NSArray *cookies = [NSArray arrayWithObjects:cookie.name, cookie.value, sessionOnly, cookie.domain, cookie.path, isSecure, nil];
                [[NSUserDefaults standardUserDefaults] setObject:cookies forKey:@"cookies"];
                break;
            }
        }
    }
    
    [webViewTarget stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
    [webViewTarget stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    self.navigationItem.title= [webViewTarget stringByEvaluatingJavaScriptFromString:@"document.title"];
    NSLog(@"title:%@",[webViewTarget stringByEvaluatingJavaScriptFromString:@"document.title"]);
    NSString *titleString = [webViewTarget stringByEvaluatingJavaScriptFromString:@"document.title"];
    //注销登录状态，清除cookie
    if ([[webViewTarget stringByEvaluatingJavaScriptFromString:@"document.title"] isEqualToString:@"正在注销登录状态"]) {
        [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"cookies"];
    }
    
    //页面背景色
    [baseWebView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='#FFFFFF'"];
    
    
    //下一个请求在新Web中打开
    if (!self.AlwaysInThisWebView) {
        OpenUrlInNewWeb=YES;
    }
    
    if ([urlStr rangeOfString:@"activities/detail"].location != NSNotFound||[urlStr rangeOfString:@"Activities/Detail"].location != NSNotFound) {
        [self.view addSubview:self.rightBtn];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [baseWebView stringByEvaluatingJavaScriptFromString:@"function assignImageClickAction(){var imgs=document.getElementsByTagName('img');var length=imgs.length;for(var i=0;i<length;i++){img=imgs[i];img.onclick=function(){window.location.href='image-preview:'+this.src}}}"];
            
            [baseWebView stringByEvaluatingJavaScriptFromString:@"assignImageClickAction();"];

            _imageUrlArray= [self getImgs];//获取所有图片链接
            [_imageUrlArray removeObjectsInRange:NSMakeRange(0, 2)];
            NSMutableArray *array=[[NSMutableArray alloc] init];
            for (NSString *string in _imageUrlArray) //剔除没有规则的图集
            {
                if ([string rangeOfString:@"180_180"].location == NSNotFound||[string rangeOfString:@"img/nopic"].location == NSNotFound) {
                    [array addObject:string];
                }
            }
            _imageUrlArray=array;
            _imageArray = [NSMutableArray array];
            NSString *path = [[NSBundle mainBundle] pathForResource:@"load" ofType:@"gif"];
            NSData *data = [NSData dataWithContentsOfFile:path];
            UIImage *image = [UIImage sd_animatedGIFWithData:data];

            for (NSInteger i = 0; i < _imageUrlArray.count; i++) {
                UIImageView *view = [[UIImageView alloc] init];
                [_imageArray addObject:view];

                UIProgressView *pv = [[UIProgressView alloc]initWithProgressViewStyle:(UIProgressViewStyleDefault)];
                [view sd_setImageWithURL:_imageUrlArray[i] placeholderImage:nil options:SDWebImageCacheMemoryOnly  progress:^(NSInteger receivedSize, NSInteger expectedSize) {

                    pv.frame = CGRectMake(0, 0, 400, 20);
                    pv.center = self.view.center;
//                    NSLog(@"%ld,%ld",receivedSize,expectedSize);
                    float currentProgress = (float)receivedSize/(float)expectedSize;
                    pv.progress = currentProgress;
                    [view addSubview:pv];

                } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    [pv removeFromSuperview];

                }];


                [view sd_setImageWithURL:_imageUrlArray[i] placeholderImage:image];
                [contenterView addSubview:view];
                
            }
        });
    }
    if ([titleString isEqualToString:@"IIS 10.0 详细错误 - 404.0 - Not Found"]) {
        UIButton *leftReturnBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        leftReturnBtn.frame = CGRectMake(20, 20, 30, 30);
        leftReturnBtn.hidden = NO;
        [leftReturnBtn setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
        [self.view addSubview:leftReturnBtn];
       
        [leftReturnBtn addTarget:self action:@selector(returnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    if ([titleString isEqualToString:@"礼包详情-众乐城"]) {
        [self.view addSubview:self.rightBtn];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [baseWebView stringByEvaluatingJavaScriptFromString:@"function assignImageClickAction(){var imgs=document.getElementsByTagName('img');var length=imgs.length;for(var i=0;i<length;i++){img=imgs[i];img.onclick=function(){window.location.href='image-preview:'+this.src}}}"];
            
            [baseWebView stringByEvaluatingJavaScriptFromString:@"assignImageClickAction();"];
            //
            [ webViewTarget stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止用户选择
            [webViewTarget stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout=‘none‘;"];//禁止长按
            
            _imageUrlArray= [self getImgs];//获取所有图片链接
            [_imageUrlArray removeObjectsInRange:NSMakeRange(0, 2)];
            _imageUrlArray2 = [[ NSMutableArray alloc] init];
            for (NSString *string in _imageUrlArray) //剔除没有规则的图集
            {
                if ([string rangeOfString:@"eidtor/image"].location != NSNotFound) {
                    [_imageUrlArray2 addObject:string];
                }
            }
            
            _imageUrlArray=_imageUrlArray2;
//            NSLog(@"1:%@",_imageUrlArray);
            _imageArray = [NSMutableArray array];
            for (NSInteger i = 0; i < _imageUrlArray.count; i++) {
                UIImageView *view = [[UIImageView alloc] init];
                [_imageArray addObject:view];
                UIProgressView *pv = [[UIProgressView alloc]initWithProgressViewStyle:(UIProgressViewStyleDefault)];
                [view sd_setImageWithURL:_imageUrlArray[i] placeholderImage:nil options:SDWebImageCacheMemoryOnly  progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                    
                    pv.frame = CGRectMake(0, 0, 400, 20);
                    pv.center = self.view.center;
//                    NSLog(@"%ld,%ld",receivedSize,expectedSize);
                    float currentProgress = (float)receivedSize/(float)expectedSize;
                    pv.progress = currentProgress;
                    [view addSubview:pv];
                    
                } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    [pv removeFromSuperview];
                    
                }];
                
                [contenterView addSubview:view];
            }
        });
    }
    
    if ([urlStr rangeOfString:@"account/InvitationReg"].location !=NSNotFound||[urlStr rangeOfString:@"account/invitationreg"].location !=NSNotFound) {
        __unsafe_unretained typeof(self)weakSelf = self;
        //    NSLog(@"UserAgent = %@", [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"]);
        [self getHerf:webViewTarget];
        //从webview中获得JSContext对象
        JSContext *context = [baseWebView  valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        //这是截获a标签的事件，处理回调
        
        context[@"callOC"] = ^() {
            NSArray *args = [JSContext currentArguments];
            if(args.count>0){
                JSValue *jsv=args[0];
                NSString *urlString=[jsv toString];
                baseUrl = urlString;
                if ([urlString rangeOfString:@"home/index"].location !=NSNotFound) {
                    [baseWebView goBack];
                    [baseWebView goBack];
                    
                }
                else if ([urlString rangeOfString:@"user/index"].location !=NSNotFound) {
                    [baseWebView goBack];
                    
                }
                else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.actionSheet showInView:weakSelf.view];
                    });
                }
            }
        };
    }
    
    //一次加载是刷新
    ShowFullLoadingView=NO;
    
}

#pragma mark - UIWebViewDelegate

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error

{
    
    //    if (firstTimaIntoWebView) {
    //        firstTimaIntoWebView = NO;
    //    }else{
    //
    //
    //        if (loadingView!=nil) {
    //            [webView setHidden:NO];
    //            [self hideLoadingView];
    //        }
    //
    //
    //        [webView.scrollView.mj_header endRefreshing];
    //
    //        [self showMessage:@"网络不佳" time:1.0];
    //
    ////        [self showAlertForSelf:@"网络请求失败，请检查您的网络设置" :10000];
    //
    //
    //        NSLog(@"网络异常");
    //    }
    
    
}
-(void)webViewDidStartLoad:(UIWebView *)webView
{
    timeOut = true;
    timer = [NSTimer scheduledTimerWithTimeInterval:8 target:self selector:@selector(timeAction) userInfo:nil repeats:NO];
}
-(void)timeAction{
    if (timeOut) {
        NSLog(@"请求超时");
        timeOut = NO;
        [baseWebView stopLoading];
        
        
        if (loadingView!=nil) {
            [baseWebView setHidden:NO];
            [self hideLoadingView];
        }
        
        
        [baseWebView.scrollView.mj_header endRefreshing];
        
        [self showMessage:@"网络不佳,加载超时" time:1.0];
        
        //            [self showAlertForSelf:@"网络请求失败，请检查您的网络设置" :10000];
        
        
        NSLog(@"网络异常");
        
        
    }
    
    [timer invalidate];
}
-(void)hideLoadingView
{
    if (loadingView!=nil) {
        [loadingView removeFromSuperview];
    }
}
#pragma mark - NJKWebViewProgress代理方法
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_progressView setProgress:progress animated:YES];
    
}
-(void)refleshWeb
{
    OpenUrlInNewWeb = NO;
    ShowFullLoadingView=NO;
    [baseWebView reload];
}
-(void)webViewLoadURL:(NSString *) urlString
{
    if (defaultUrl==nil || [defaultUrl isEqualToString:@""])
    {
        defaultUrl=urlString;
    }
    ShowFullLoadingView=YES;
    //注意URL带有中文得要转换
    [baseWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]]];
}
-(void)refleshWebWithLoadingView
{
    OpenUrlInNewWeb = NO;
    ShowFullLoadingView=YES;
    [baseWebView reload];
}


#pragma mark - 微信支付处理方法

-(void)dealWithWeiXinPay:(NSString*)stringUrl
{
    NSRange range = [stringUrl rangeOfString:@"prepayid="]; //现获取要截取的字符串位置
    NSString * result = [stringUrl substringFromIndex:range.location+9]; //截取字符串
    
    NSLog(@"URL截取传值部分：%@",result);
    
    //二次切分参数
    NSArray *array2 = [result componentsSeparatedByString:@"%7C"];
    if(array2.count==5){
        
        NSString* prepayid = array2[0];
        NSString* noncestr=array2[1];
        NSString* timeStamp=array2[2];
        NSString* package=array2[3];
        NSString* sign=array2[4];
        
        //调起微信支付
        PayReq* req             = [[PayReq alloc] init];
        req.openID              = WeiXin_AppID;//appid
        req.partnerId           = WeiXin_PartnerID;//partnerid
        req.prepayId            = prepayid;//prepayid
        req.nonceStr            = noncestr;//noncestr
        req.timeStamp           = [timeStamp intValue];
        req.package             = package;//package
        req.sign                = sign;//sign
        [WXApi sendReq:req];
        //日志输出
        NSLog(@"微信支付请求参数\nappid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",req.openID,req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
    }else{
        NSLog(@"不能支付：传值数量不对应！");
    }
}

- (void)showAlert:(NSString *)message{
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"提示"
                          message:message
                          delegate:nil
                          cancelButtonTitle:@"确定"
                          otherButtonTitles:nil
                          ];
    [alert show];
}

- (void)showAlertForSelf:(NSString *)message :(int)tag{
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"提示"
                          message:message
                          delegate:self
                          cancelButtonTitle:@"确定"
                          otherButtonTitles:nil
                          ];
    alert.tag = tag;
    [alert show];
}
- (void)showAlertSelectWithTitle:(NSString *)message title:(NSString*)title
                         leftBtn:(NSString*)leftBtn  rightBtn:(NSString*)rightBtn :(int)tag{
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:title
                          message:message
                          delegate:self
                          cancelButtonTitle:leftBtn
                          otherButtonTitles:rightBtn,nil
                          ];
    alert.tag = tag;
    [alert show];
}





#pragma mark - alertView
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==10000) {
        
        [self exitApplication];
    }
    
    if (alertView.tag == 1) {
        if (buttonIndex==0) {//退出程序
            [self exitApplication];
        }
        if (buttonIndex==1) {//确定立即升级
            //            [self jumpToUpdateWeb];
            
            NSURL * urlSetting = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            
            if([[UIApplication sharedApplication] canOpenURL:urlSetting]) {
                
                NSURL*urlSetting =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:urlSetting];
                
            }
        }
    }
}




- (void)showMessage:(NSString *)string time:(float)delay{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    // Configure for text only and offset down
    hud.mode = MBProgressHUDModeText;
    hud.labelText = string;
    hud.margin = 10.f;
    hud.yOffset = 0.0f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:delay];
}



- (void)exitApplication {
    
    AppDelegate *app = (AppDelegate*)[UIApplication sharedApplication].delegate;
    UIWindow *window = app.window;
    
    [UIView animateWithDuration:1.0f animations:^{
        window.alpha = 0;
        window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
    } completion:^(BOOL finished) {
        exit(0);
    }];
    //exit(0);
    
}

//-(void)longPressToDo:(UILongPressGestureRecognizer *)gesture
//{
//    if(gesture.state == UIGestureRecognizerStateBegan)
//    {
//        [self.actionSheet showInView:self.view];
//    }
//}


-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = baseUrl;
    
    }else if(buttonIndex == 1){
        NSURL *urlToShare = [NSURL URLWithString:baseUrl];
        NSString *textToShare = @"邀请您注册众乐城";
        UIImage *imageToShare = [UIImage imageNamed:@"AppIcon"];
        NSArray *activityItems = @[textToShare,imageToShare, urlToShare];
        //自定义 customActivity继承于UIActivity,创建自定义的Activity加在数组Activities中。
        UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
        //不出现在活动项目
        activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
        [self presentViewController:activityVC animated:YES completion:nil];
        // 分享之后的回调
        activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
            if (completed) {
                NSLog(@"completed");
                //分享 成功
            } else  {
                NSLog(@"cancled");
                //分享 取消
            }
        };
        
    }else {
        
    }
}

#pragma mark  注入a标签链接回调,html不响应事件，截取事件给oc代码响应
-(void)getHerf:(UIWebView *)view{
    NSString *hrefStr=@"var script = document.createElement('script');"
    "script.type = 'text/javascript';"
    "script.text = \"function getHerdf(){"
    "if(document.getElementsByTagName('a').length>0){"
    "for(var i=0;i<document.getElementsByTagName('a').length;i++){"
    "var ka=document.getElementsByTagName('a')[i];"
    "ka.onclick=function (){"
    "if(this.href.indexOf('http')==0){"
    "callOC(this.href);"
    "return false;"
    "}"
    "}"
    "}"
    "}"
    "}\";"
    "document.getElementsByTagName('head')[0].appendChild(script);";
    [view stringByEvaluatingJavaScriptFromString:hrefStr];
    [view stringByEvaluatingJavaScriptFromString:@"getHerdf();"];
}

- (UIActionSheet *)actionSheet {
    if (!_actionSheet) {
        _actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"是否复制分享链接地址？", @"分享给好友",nil, nil];
    }
    return _actionSheet;
}

//获取某个标签的结点个数
- (int)nodeCountOfTag:(NSString *)tag {
    
    NSString *jsString = [NSString stringWithFormat:@"document.getElementsByTagName('%@').length", tag];
    int len = [[baseWebView stringByEvaluatingJavaScriptFromString:jsString] intValue]; return len;
}
//获取所有图片链接
- (NSMutableArray *)getImgs
{
    NSMutableArray *arrImgURL = [[NSMutableArray alloc] init];
    int node = [self nodeCountOfTag:@"img"];
    for (int i = 0; i < node; i++)
    {
        NSString *jsString = [NSString stringWithFormat:@"document.getElementsByTagName('img')[%d].src", i];
        NSString *img = [baseWebView stringByEvaluatingJavaScriptFromString:jsString];
        [arrImgURL addObject:img];
    }
    return arrImgURL;
}

#pragma mark - SDPhotoBrowserDelegate

- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
    NSString *imageName = _imageUrlArray[index];
    NSURL *url = [NSURL URLWithString:imageName];
    
    return url;
}

- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    UIImageView *imageView = _imageArray[index];
    
    return imageView.image;
}

- (UIButton *)rightBtn {
    if (!_rightBtn) {
        _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightBtn setTitle:@" " forState:UIControlStateNormal];
        _rightBtn.frame = CGRectMake(SCREEN_WIDTH - 50 , 10, 40, 40);
        [_rightBtn addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightBtn;
}

- (void)rightAction:(id)sender {
    //     [YBPopupMenu showRelyOnView:sender titles:TITLES icons:ICONS menuWidth:100 delegate:self];
    
    //推荐用这种写法
    
    CGPoint p = CGPointMake(SCREEN_WIDTH-25, 15);
    [YBPopupMenu showAtPoint:p titles:TITLES icons:ICONS menuWidth:110 otherSettings:^(YBPopupMenu *popupMenu) {
        popupMenu.dismissOnSelected = NO;
        popupMenu.isShowShadow = YES;
        popupMenu.delegate = self;
        popupMenu.offset = 20;
        popupMenu.type = YBPopupMenuTypeDefault;
        
        popupMenu.rectCorner = UIRectCornerBottomLeft | UIRectCornerBottomRight|UIRectCornerTopLeft|UIRectCornerTopRight;
        _popupMenu = popupMenu;
    }];
}

#pragma mark - YBPopupMenuDelegate
- (void)ybPopupMenuDidSelectedAtIndex:(NSInteger)index ybPopupMenu:(YBPopupMenu *)ybPopupMenu
{
    
    switch (index) {
        case 0:
        {
            [baseWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.zlc99.com/"]]];
        }
            break;
        case 1:
        {
            [baseWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.zlc99.com/help/index.html"]]];
        }
            break;
        case 2:
        {
            [baseWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.zlc99.com/account/invitationreg.html"]]];
        }
            break;
            
        default:
            break;
    }
    [_popupMenu dismiss];
}

- (void)returnAction:(UIButton*)sender {
    [baseWebView goBack];
    sender.hidden = YES;
}

@end
